import { think } from 'thinkjs';
// import RestModelClass, { RestOption } from "src/types/utils/rest";
import Base, { ServiceOption } from '../../../../../service/base';
import mongoose from 'mongoose';
import mongo from '../../../../../utils/mongo';
import { syncValidate } from '../../../../utils/validate';

import { ISession, SchemaSession } from '../../types/model/Session';
import { IServiceCloudImSessionFetchParams, IServiceCloudImSessionFetchResult } from '../../types/service/Session';
import SessionModel from '../model/session';
import { ImConnectServiceClass } from './connect';
import { IImDeviceEvent, IImDeviceEventSetCurrSession, IImDeviceEventUpdateSessionField, IImDeviceEventInvokeDeleteSession } from '../../types';

export class SessionServiceClass extends Base<ISession> {
  constructor(option: ServiceOption) {
    super(option);
  }

  async fetch({ account, currentPage, pageSize }: IServiceCloudImSessionFetchParams): Promise<IServiceCloudImSessionFetchResult> {
    const SessionModel = mongo.model<ISession & mongoose.Document>('session', SchemaSession);
    let where = {
      account,
    };
    const sessions = await SessionModel.find(where)
      .sort({ updateTime: -1 })
      .skip((currentPage - 1) * pageSize)
      .limit(pageSize)
      .exec();
    return {
      sessions,
    };
  }

  /* 进入会话（清空未读、更新时间） */
  async setCurrSession({ sessionId, account }: IImDeviceEventSetCurrSession) {
    // 更新会话清空未读消息数
    const { session } = await SessionModel.createOrUpdateSession({
      sessionId,
      account,
      unreadNum: 0,
    });
    // 推送至其他端
    const connectService = think.service('cloudim_connect') as ImConnectServiceClass;
    const { online } = await connectService.sendMessageToClient({
      account,
      message: {
        type: 'session',
        session,
      },
    });
  }

  /* 更新会话字段 */
  async updateSession({ sessionId, account, isTop, topCustom }: IImDeviceEventUpdateSessionField) {
    // 更新会话清空未读消息数
    const { session } = await SessionModel.createOrUpdateSession({
      sessionId,
      account,
      isTop,
      topCustom
    });
    // 推送至其他端
    const connectService = think.service('cloudim_connect') as ImConnectServiceClass;
    const { online } = await connectService.sendMessageToClient({
      account,
      message: {
        type: 'session',
        session,
      },
    });
  }

  /* 删除会话 */
  async deleteSession({ account, scene, to }: IImDeviceEventInvokeDeleteSession) {
    // 更新会话清空未读消息数
    await SessionModel.deleteSession(
      account,
      scene,
      to
    );
    // 推送至其他端
    const connectService = think.service('cloudim_connect') as ImConnectServiceClass;
    const { online } = await connectService.sendMessageToClient({
      account,
      message: {
        type: 'onDeleteSession',
        scene,
        to
      },
    });
  }

}

export default SessionServiceClass;
